package com.apache.uct.common;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.apache.api.vo.ResultEntity;
import com.apache.client.UctCoreClient;
import com.apache.uct.common.entity.Role;

/**
 * PBO对接SSO工具类
 * @author lvcai
 */
public class PBOSSOTools {

	/**
	 * 获得登录用户
	 * 
	 * @param request 请求对象
	 * @return LoginUser 登录对象
	 */
	public static LoginUser getLoginUser(HttpServletRequest request) {
		LoginUser loginUser = (LoginUser) request.getSession().getAttribute("loginUser");
		return loginUser;
	}

	/**
	 * 根据userEname从用户中心查询登录信息
	 * @param userEname
	 * @return
	 */
	public static LoginUser getLoginUserFromUserCenter(String userEname, String token) {
		LoginUser loginUser = null;
		if (ToolsUtil.isNotNull(userEname)) {
			//重新从用户中心获取loginUser
			loginUser = UctCoreClient.getLoginUserFromUserCenterSso(userEname, token);
		}
		return loginUser;
	}

	/**
	 * description:  获取当前用户的角色列表
	 * @param request
	 * @return   
	 * @author Hou Dayu  
	 * @update 2016-1-29
	 */
	public static List<Role> getRolesForLoginUser(HttpServletRequest request) {
		LoginUser user = getLoginUser(request);
		if (!ToolsUtil.isEmpty(user)) {
			List<Role> roles = (List<Role>) request.getSession().getAttribute("loginUserRoles");
			if (ToolsUtil.isEmpty(roles)) {
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("userEname", user.getUserEname());
				ResultEntity entity = UctCoreClient.searchRoleByReflect(map);
				if ("true".equals(entity.getResult()) && !ToolsUtil.isEmpty(entity.getEntity())) {
					request.getSession().setAttribute("loginUserRoles", entity.getEntity());
					return (List<Role>) entity.getEntity();
				}
			}
		}
		return null;
	}

	/**
	 * description:  根据token从uc获取用户信息
	 * @param token
	 */
	public static LoginUser getLoginUserFromUserCenterSso(String token) {
		LoginUser loginUser = null;
		if (ToolsUtil.isNotNull(token)) {
			loginUser = UctCoreClient.getLoginUserFromUserCenterSso("", token);
		}
		return loginUser;
	}

}
